package cloud.shyidong.admin.system.service;

import cloud.shyidong.core.context.ContextHolder;
import cloud.shyidong.core.exception.BusinessException;
import cloud.shyidong.core.request.LongIdRequest;
import cloud.shyidong.core.service.AbstractService;
import cloud.shyidong.core.util.CollectionUtils;
import cloud.shyidong.core.util.DateUtils;
import cloud.shyidong.core.util.MD5Utils;
import cloud.shyidong.system.dao.SystemRoleDao;
import cloud.shyidong.system.dao.SystemUserDao;
import cloud.shyidong.system.dao.SystemUserRoleDao;
import cloud.shyidong.system.entity.SystemRoleEntity;
import cloud.shyidong.system.entity.SystemUserEntity;
import cloud.shyidong.system.entity.SystemUserRoleEntity;
import cloud.shyidong.system.request.SystemUserInsertRequest;
import cloud.shyidong.system.request.SystemUserPageRequest;
import cloud.shyidong.system.request.SystemUserUpdateRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表业务处理
 * </p>
 *
 * @author syd
 * @since 2023-05-31 13:14:46
 */
@Service
public class SystemUserService extends AbstractService<SystemUserDao, SystemUserEntity, LongIdRequest, SystemUserInsertRequest, SystemUserUpdateRequest, SystemUserPageRequest> {
    
    private SystemRoleDao systemRoleDao;
    
    private SystemUserRoleDao systemUserRoleDao;
    
    @Autowired
    public void setSystemRoleDao(SystemRoleDao systemRoleDao) {
        this.systemRoleDao = systemRoleDao;
    }
    
    @Autowired
    public void setSystemUserRoleDao(SystemUserRoleDao systemUserRoleDao) {
        this.systemUserRoleDao = systemUserRoleDao;
    }
    
    @Override
    public void beforeInsert(SystemUserInsertRequest insertRequest) {
        
        if (!insertRequest.getPassword().equals(insertRequest.getConfirmPassword())) {
            throw BusinessException.from("登录密码与确认密码不一致，请重新输入");
        }
        
        if (this.getDao().selectCount(new QueryWrapper<SystemUserEntity>().eq("username", insertRequest.getUsername())) > 0) {
            throw BusinessException.from("登录名称重复，请更新其它登录名称");
        }
        insertRequest.setPassword(MD5Utils.md5Hex(insertRequest.getPassword()));
    }
    
    @Override
    public void afterInsert(SystemUserInsertRequest insertRequest, SystemUserEntity systemUserEntity) {
        
        insertRole(systemUserEntity.getId(), insertRequest.getRoleIds());
        
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public SystemUserEntity update(SystemUserUpdateRequest updateRequest) {
        
        beforeUpdate(updateRequest);
        
        SystemUserEntity systemUserEntity = getDao().selectById(updateRequest.getId());
        systemUserEntity.setName(updateRequest.getName());
        systemUserEntity.setPhone(updateRequest.getPhone());
        systemUserEntity.setEmail(updateRequest.getEmail());
        systemUserEntity.setSortIndex(updateRequest.getSortIndex());
        systemUserEntity.setRemark(updateRequest.getRemark());
        systemUserEntity.setUpdateUser(ContextHolder.getContext().getUserId());
        systemUserEntity.setUpdateTime(DateUtils.getNow());
        if (getDao().updateById(systemUserEntity) == 0) {
            throw BusinessException.from("用户更新失败");
        }
        
        afterUpdate(updateRequest, systemUserEntity);
        
        systemUserEntity.setPassword("******");
        return systemUserEntity;
    }
    
    @Override
    public void afterUpdate(SystemUserUpdateRequest updateRequest, SystemUserEntity systemUserEntity) {
        
        //删除角色，再新增角色
        systemUserRoleDao.delete(new UpdateWrapper<SystemUserRoleEntity>().eq("user_id", updateRequest.getId()));
        
        insertRole(systemUserEntity.getId(), updateRequest.getRoleIds());
    }
    
    private void insertRole(Long id, List<Long> roleIds) {
        
        if (CollectionUtils.isEmpty(roleIds)) {
            return;
        }
        
        for (Long roleId : roleIds) {
            
            SystemUserRoleEntity systemUserRoleEntity = new SystemUserRoleEntity();
            systemUserRoleEntity.setUserId(id);
            systemUserRoleEntity.setRoleId(roleId);
            systemUserRoleDao.insert(systemUserRoleEntity);
            
        }
        
    }
    
    @Override
    public Map<String, Object> view(LongIdRequest idRequest) {
        Map<String, Object> result = super.view(idRequest);
        List<SystemUserRoleEntity> systemUserRoleEntities = systemUserRoleDao.selectList(new QueryWrapper<SystemUserRoleEntity>().eq("user_id", idRequest.getId()));
        if (CollectionUtils.isNotEmpty(systemUserRoleEntities)) {
            List<SystemRoleEntity> systemRoleEntities = new ArrayList<>();
            for (SystemUserRoleEntity systemUserRoleEntity : systemUserRoleEntities) {
                SystemRoleEntity systemRoleEntity = systemRoleDao.selectById(systemUserRoleEntity.getRoleId());
                systemRoleEntities.add(systemRoleEntity);
            }
            result.put("roles", systemRoleEntities);
        }
        return result;
    }
    
}
